<!--添加产品组件-->
<template>
  <div>
    <el-dialog
      :title="title"
      :visible="dialogVisible"
      @close="cancelDialog"
      width="1200px"
      class="edit-form"
    >
      <!-- 搜索模块 -->
      <SearchForm
        show-collapse
        :data="computedProductListSearchForm"
        :compact-data="compactProductListSearchForm"
        @remoteMethod="remoteMethod"
        @searchForm="searchForm"
        @resetForm="resetForm"
        ref="search"
      />
      <!-- 列表模块 -->
      <el-editable
        ref="productTable"
        class="hospital-edit-box"
        v-loading="productLoading"
        :data="productList"
        height="400"
        :columns="computedProductListColumns"
        @selection-change="handleSelectionChange"
      >
        <template
          slot="default-registrationNumber"
          slot-scope="scope">
          <div>
            <cell-registration
              :regis-no="scope.row.registrationNumber"
              :content="'注册证已过期，点击查看详细信息'"
              :status="scope.row.expireStatus"
              :regis-data="scope.row.registInfo"
            />
          </div>
        </template>
        <template
          slot="default-registNo"
          slot-scope="scope">
          <div>
            <cell-registration
              :regis-no="scope.row.registNo"
              :content="'注册证已过期，点击查看详细信息'"
              :status="scope.row.expireStatus"
              :regis-data="scope.row.registInfo"
            />
          </div>
        </template>
        <template
          slot="default-purchaseNum"
          slot-scope="scope">
          <el-input-number
            v-model="scope.row.purchaseNum"
            @change="resetIllegalInput(scope.row,$event)"
            size="mini"
            :min="1"
            :max="9999999"
            label="描述文字"
            step-strictly
          />
        </template>
        <template
          slot="default-returnNum"
          slot-scope="scope">
          <el-input-number
            v-model="scope.row.returnNum"
            @change="resetIllegalInput(scope.row,$event)"
            size="mini"
            :min="1"
            :max="9999999"
            label="退货数量"
          />
        </template>
        <!-- 单价 -->
        <template
          slot="default-buyPrice"
          slot-scope="scope">
          <span>{{ Number(scope.row.buyPrice).toFixed(2) }}</span>
        </template>
      </el-editable>
      <!-- 分页模块 -->
      <el-pagination
        align="right"
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="totalElements"
      />
      <div
        slot="footer"
        class="dialog-footer">
        <el-button @click="cancelDialog">取消</el-button>
        <el-button
          type="primary"
          @click="confirmDialog">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  commonProductListColumns,
  returnProductListColumns,
  commonProductListSearchForm,
  returnProductListSearchForm,
  commonProductListDisTributorColumns,
  commonDisButorProductListSearchForm,
  addFollowTheStageDistributorSide,
  addFollowTheStageDistributorSideColumns
} from './const'
import ElEditable from '@components/el-editable'
import SearchForm from '@components/businesscomponents/search'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import CellRegistration from '@/moduleComponents/common/detail/cell-registration'
import { hasIn } from 'lodash'
import { authItemCommonNameQuery, getPlatProdCategoryTypeTree } from '@const/prdutCentApi'
import { YyPssPsPurchaseOrderAddOrder } from '@const/beforeSettleApi'
import { authItemauthItemCommonNameQuery, enumSelectorhosDealerSuperDealer } from '@const/productCenterApiV2'
export default {
  name: 'AddProductDialog',
  components: {
    SearchForm,
    ElEditable,
    CellRegistration
  },
  props: {
    title: {
      type: String,
      default: '添加采购产品'
    },
    supplierId: {
      type: String,
      default: ''
    },
    supplierName: {
      type: String,
      default: ''
    },
    dialogVisible: {
      type: Boolean,
      default: false
    },
    queryUrl: {
      // 产品列表查询url
      type: String,
      default: '#'
    },
    queryMethod: {
      type: String,
      default: 'get'
    },
    extraQuery: {
      // 要添加的额外请求参数
      type: Object,
      default: () => {}
    },
    currentProducts: {
      // 已经添加到页面中的产品，用于处理接口以加数据中的选中状态
      type: Array,
      default: () => []
    },
    type: {
      // 新增订单类型（return: 退货、或者没有类型，采用公共表头数据）
      type: String,
      default: ''
    },
    priceModelType: {
      // 是否要获取到模板价格
      type: String,
      default: () => ''
    }
  },
  data () {
    return {
      commonProductListColumns, // 添加采购产品弹窗列表表头
      returnProductListColumns,
      commonProductListSearchForm, // 添加采购产品弹窗搜索字段
      addFollowTheStageDistributorSide,
      addFollowTheStageDistributorSideColumns,
      returnProductListSearchForm,
      dialogShow: true,
      curPage: 1,
      PAGE_NUMBER,
      PAGINATION_LAYOUT,
      pageSize: PAGE_NUMBER[0],
      totalElements: 0,
      productList: [], // 添加采购产品弹窗中，根据筛选条件查询出的可以采购的产品列表
      searchQuery: {},
      productLoading: false,
      productSelectedList: [],
      allSelectedList: [], // 全部选中的项，初始值总是为创建订单页面中已经有的项
      addedList: this.currentProducts, // 已经添加到外部页面中的产品列表
      commonProductListDisTributorColumns,
      commonDisButorProductListSearchForm
    }
  },
  computed: {
    compactProductListSearchForm () {
      return this.computedProductListSearchForm.slice(0, 2)
    },
    // 计算查询条件表单
    computedProductListSearchForm () {
      // followTheStage这个字段标识是从“配送商新建跟台”过来的
      if (this.type === 'return') {
        return this.returnProductListSearchForm
      } else if (this.type === 'distributor') {
        return this.commonDisButorProductListSearchForm
      } else if (this.type === 'hospital') {
        return this.commonProductListSearchForm
      } else if (this.type === 'followTheStage') {
        return this.addFollowTheStageDistributorSide
      }
    },
    // 计算表格列
    computedProductListColumns () {
      // followTheStage这个字段标识是从“配送商新建跟台”过来的
      if (this.type === 'return') {
        return this.returnProductListColumns
      } else if (this.type === 'distributor') {
        return this.commonProductListDisTributorColumns
      } else if (this.type === 'hospital') {
        return this.commonProductListColumns
      } else if (this.type === 'followTheStage') {
        return this.addFollowTheStageDistributorSideColumns
      }
    }
  },
  watch: {
    dialogVisible (visible) {
      if (visible) {
        this.getProductList()
        this.productQueryColumns() // 产品分类
      }
    },
    currentProducts (val) {
      this.addedList = val
    }
  },
  methods: {
    getProductList () {
      const postData = {
        ...this.extraQuery,
        ...this.searchQuery,
        page: this.curPage,
        pageSize: this.pageSize,
        priceModelType: this.priceModelType
      }
      const url = this.queryUrl
      const method = '$' + this.queryMethod
      this.productLoading = true
      this.$axios[method](url, postData)
        .then(res => {
          this.productList = res.payload.content
          this.totalElements = res.payload.totalElements
          this.setCurrentSelection()
        })
        .finally(() => {
          this.productLoading = false
        })
    },
    productQueryColumns () {
      this.$axios
        .$get(getPlatProdCategoryTypeTree)
        .then(res => {
          commonDisButorProductListSearchForm[1].options = res.payload
        })
        .catch(e => {
          console.log(e)
        })
    },
    resetIllegalInput (row, value) {
      if (value % 1 !== 0) {
        row.purchaseNum = Math.round(value)
        row.returnNum = Math.round(value)
      }
    },
    remoteMethod (value, key) {
      if (key === 'upEnterpriseId') {
        this.getupEnterprise(value)
      }
    },
    getupEnterprise (value) {
      const postData = {
        upEnterpriseName: value
      }
      console.log(value)
      const item = this.commonDisButorProductListSearchForm.find(item => item.key === 'upEnterpriseId')
      // this.$axios.$post(enumSelectorhosDealerSuperDealer, postData)
      this.$axios({
        method: 'post',
        data: postData,
        url: enumSelectorhosDealerSuperDealer
      })
        .then(res => {
          let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
          const nameList = obj.content
          const options = nameList.map(item => {
            return {
              label: item.value,
              value: item.id
            }
          })
          console.log(item, 'options')
          this.$set(item, 'options', options)
        })
    },
    getAuthItemName (value) {
      const postData = {
        ...this.extraQuery,
        name: value,
        pageSize: 9999
      }
      const item = this.commonProductListSearchForm.find(
        item => item.key === 'idList'
      )
      this.$set(item.attr, 'loading', true)
      this.$axios
        .$post(authItemauthItemCommonNameQuery, postData)
        .then(res => {
          const nameList = res.payload.content
          const options = nameList.map(item => {
            return {
              label: item.value,
              value: [item.id]
            }
          })
          this.$set(item, 'options', options)
        })
        .catch(e => {})
        .finally(() => {
          this.$set(item.attr, 'loading', false)
        })
    },
    searchForm (condition) {
      this.curPage = 1
      this.searchQuery = condition
      this.getProductList()
    },
    resetForm (condition) {
      this.curPage = 1
      this.searchQuery = condition
      this.getProductList()
    },
    confirmDialog () {
      this.$emit('confirmDialog', this.productSelectedList)
    },
    cancelDialog () {
      this.productList = []
      this.allSelectedList = []
      this.$emit('cancelDialog')
      this.$refs.search.reset()
    },
    handleSizeChange (size) {
      this.pageSize = size
      this.getProductList()
      this.updateAllSelectedList() // 换页就更新全部选中项数组
    },
    handleCurrentChange (curPage) {
      this.curPage = curPage
      this.getProductList()
      this.updateAllSelectedList() // 改变页大小也更新全部选中项数组
    },
    handleSelectionChange (selection) {
      selection.map(item => {
        if (!item.purchaseNum) item.purchaseNum = 1
        if (!item.returnNum) item.returnNum = 1
      })
      this.productSelectedList = selection
    },
    updateAllSelectedList () {
      // 更新allSelectedList数组，在换页和改变每页大小的时候执行
      this.productSelectedList.forEach(item => {
        let findItem = ''
        if (this.type === 'hospital') {
          findItem = this.allSelectedList.find(
            selected => selected.dealerAuthItemId === item.dealerAuthItemId
          )
        } else if (this.type === 'distributor') {
          findItem = this.allSelectedList.find(
            selected => selected.id === item.id
          )
        }
        this.isAddedList(findItem, item)
      })
    },
    isAddedList (findItem, item) {
      if (!findItem) {
        // 没有就添加
        this.allSelectedList.push(item)
      } else {
        // 有就更新数量
        findItem.purchaseNum = item.purchaseNum
        findItem.returnNum = item.returnNum
      }
    },
    setCurrentSelection () {
      // 如果当前项已经在外部页面中了或者已经被选中过就选中
      this.addedList.forEach(item => {
        const findItem = this.productList.find(
          product => product.id === item.authProdId || product.id === item.id
        )
      })
      this.allSelectedList.forEach(selected => {
        const findItem = this.productList.find(
          product => selected.id === product.id
        )
      })
    }
  }
}
</script>
<style lang="less">
</style>
